package com.infotel.chat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Date;

public class ThreadServeur extends Thread {
    Socket socketServeur;
    Chat chat;

    public ThreadServeur(Socket socketServeur, Chat chat) {
        this.socketServeur = socketServeur;
        this.chat = chat;
    }

    public void run() {
        try {
            InputStream fluxLecture = socketServeur.getInputStream();
            OutputStream fluxEcriture = socketServeur.getOutputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    fluxLecture, "UTF-8"));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                    fluxEcriture, "UTF-8"));

//            SimpleDateFormat sdf = new SimpleDateFormat(
//                    "yyyy-MM-dd'T'HH:mm:ss.SSS");
            boolean fin = false;
            while (!fin) {
                switch (br.readLine()) {
                case "ENVOIE MESSAGE":
                    String username = br.readLine();
                    String message = br.readLine();
                    Users user = new Users(username);
                    chat.getUsers().add(user);
                    chat.getMessages().add(
                            new Messages(user, new Date(), message));
                    bw.write("Ok\n");
                    bw.flush();
                    break;
                case "LISTE MESSAGES":
                    chat.marshallMessages(fluxEcriture);
                    chat.marshallMessages(new FileOutputStream(new File("C:\\a_workspace\\Multimedia\\src\\com\\infotel\\chat\\chat.xml")));
                    break;
                case "FIN":
                    fin = true;
                    break;
                default:
                    bw.write("ERROR\n");
                    bw.flush();
                }
            }
            br.close();
            bw.close();
            socketServeur.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
